package com.quarkus.resource;

import com.quarkus.bean.Fruit;
import com.quarkus.servcie.FruitService;
import lombok.extern.slf4j.Slf4j;
import org.glassfish.json.MapUtil;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.Validator;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.stream.Collectors;

@Slf4j
@Path("/fruits")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class FruitResource {

    @Inject
    Validator validator;

    @Inject
    FruitService fruitService;

    private final Map<String, Fruit> fruits = new HashMap<>();

    public FruitResource() {
        fruits.put("Apple", new Fruit("Apple", "Winter fruit"));
        fruits.put("Pineapple", new Fruit("Pineapple", "Tropical fruit"));
    }

    @GET
    public Map<String, Fruit> list() {
        return fruits;
    }

    @PUT
    public Map<String, Fruit> edit(Fruit fruit) {
        Set<ConstraintViolation<Fruit>> violationSet = validator.validate(fruit);
        if(!violationSet.isEmpty()){
            String message = violationSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining(", "));
            log.error("param validate error {}", message);
            return fruits;
        }
        Fruit old = fruits.get(fruit.getName());
        old.setDescription(fruit.getDescription());
        return fruits;
    }

    @POST
    public Map<String, Fruit> add(@Valid Fruit fruit) {
        fruits.put(fruit.getName(), fruit);
        return fruits;
    }

    @DELETE
    public Map<String, Fruit> delete(Fruit fruit) {
        fruits.remove(fruit.getName());
        return fruits;
    }

    @Path("test")
    @POST
    public Map<String, String> testValidate(Fruit fruit){

//        try {
            this.fruitService.validate(fruit);
//        }catch (ConstraintViolationException e){
//            log.error("catch exception");
//            e.printStackTrace();
//        }

        return null;
    }
}